package org.dromara.common.excel.core

import cn.hutool.core.collection.CollUtil
import cn.idev.excel.metadata.Head
import cn.idev.excel.write.handler.WorkbookWriteHandler
import cn.idev.excel.write.handler.context.WorkbookWriteHandlerContext
import cn.idev.excel.write.merge.AbstractMergeStrategy
import io.github.oshai.kotlinlogging.KotlinLogging
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.util.CellRangeAddress

/**
 * 列值重复合并策略
 *
 * @author Lion Li
 * @updater LikeYouDo
 */
class CellMergeStrategy(
    private val cellList: List<CellRangeAddress>,
) : AbstractMergeStrategy(), WorkbookWriteHandler {
    companion object {
        private val log = KotlinLogging.logger { }
    }

    constructor(list: List<*>, hasTitle: Boolean): this(CellMergeHandler.of(hasTitle).handle(list))

    protected override fun merge(sheet: Sheet?, cell: Cell, head: Head?, relativeRowIndex: Int?) {
        if (CollUtil.isEmpty(cellList)) {
            return
        }
        // 单元格写入了,遍历合并区域,如果该Cell在区域内,但非首行,则清空
        val rowIndex = cell.rowIndex
        for (cellAddresses in cellList) {
            val firstRow = cellAddresses.firstRow
            if (cellAddresses.isInRange(cell) && rowIndex != firstRow) {
                cell.setBlank()
            }
        }
    }

    override fun afterWorkbookDispose(context: WorkbookWriteHandlerContext) {
        if (CollUtil.isEmpty(cellList)) {
            return
        }
        // 当前表格写完后，统一写入
        for (item in cellList) {
            context.writeContext.writeSheetHolder().sheet.addMergedRegion(item)
        }
    }

}
